﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Snake.Core;
using Snake.Mapping;
using Snake.SQL;

namespace Snake.SQL.SQLNode
{
    public class Delete : DbOperate
    {
        //public readonly BracketedName Alias;

        //public readonly EntityMap EntityMap;
       // public From From;
      //  public  Where Where;
        public JoinGroup JoinGroup;

        public Delete(DbContext context) : this(context.GetEntityMap(context.EntityType), context.NextAlias())
        {
            
           
        }

        public Delete(EntityMap entityMap,BracketedName alias)
        {
            if(entityMap==null)
                throw new ArgumentNullException("entityMap");
            if(alias==null)
                throw new ArgumentNullException("alias");
            Alias = alias;
            EntityMap = entityMap;
            JoinGroup = new JoinGroup();
    
        }


        public override bool VisitPath(DbContext context, PropertyInfo[] path, out BracketedName alias, out PropertyMap map)
        {
            var entity = EntityMap;
            alias = Alias;
            map = null;

            for (var i = 0; i < path.Length - 1; i++)
            {
                var prop = path[i];
                var item = JoinGroup.FindJoin(prop);
                if (item == null)
                {
                    var reference = entity.FindReferenceMap(prop);

                    if (reference == null)
                        return false;

                    item = JoinGroup.AddJoin(alias, context.NextAlias(), reference);
                }

                alias = item.ToAlias;
                entity = item.ReferenceMap.To;
            }

            var last = path[path.Length - 1];
            map = entity.FindPropertyMap(last) ?? entity.FindReferenceMap(last);

            return true;
        }

        public override void Render(SQLWriter writer)
        {
            writer.AppendLine(SQLStrings.Delete);

            writer.AppendLine(SQLStrings.From);

            writer.AppendLine(EntityMap.Table);

            writer.AppendLine(JoinGroup);

            writer.AppendLine(Where);

           // writer.AppendLine(SQLStrings.NoLock);
         
        }
    }
}
